<template>
  <div id="content">
    <div
      id="map"
      ref="map"
    ></div>
    <code>-->haha</code>
    <label :for="speed">
      speed:&nbsp;
      <input
        id="speed"
        type="range"
        min="10"
        max="999"
        step="10"
        v-model="speed"
      />
    </label>
    <button
      id="start-animation"
      @click.stop="startButton"
    >
      {{ startbutton }}
    </button>
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View, Feature } from "ol";
import Proj from "ol/proj/Projection";
import Units from "ol/proj/Units";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Style, Stroke, Icon } from "ol/style";
import { LineString, Point, Polygon } from "ol/geom";
import XYZ from "ol/source/XYZ";
import { fromLonLat } from "ol/proj";
import { getVectorContext } from "ol/render";
// import Polyline from 'ol/format/Polyline';
// 引入轨迹经纬度的json文件
import trackCar from "../track-car.json";
export default {
  name: "track-car",
  data() {
    return {
      map: null,
      startbutton: "按钮",
      animating: false,
      speed: "60",
      now: "",
      geoMarker: {},
      styles: {},
    };
  },
  methods: {
    /**
     * 初始化一个 openlayers 地图
     */
    initMap() {
      let target = "map"; //跟页面元素的 id 绑定来进行渲染
      let tileLayer = [
        new TileLayer({
          source: new XYZ({
            url:
              "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
          }),
        }),
        this.vectorLayer,
      ];
      var proj = new Proj({
        code: "EPSG:4326",
        units: Units.DEGREES,
      });
      console.log(proj);
      let view = new View({
        center: fromLonLat([120.9800615193, 29.1326618704]),
        zoom: 14,
      });
      this.map = new Map({
        target: target,
        layers: tileLayer,
        view: view,
      });
      // 根据点数据确认窗口视图的位置
      this.map
        .getView()
        .fit(new Polygon([trackCar]).transform("EPSG:4326", "EPSG:3857"), {
          padding: [100, 100, 100, 100],
        });
    },
    /**
     * 创建轨迹的方法
     */
    addTrack() {
      let _that = this;
      // 根据经纬度点位创建线
      var routeFeature = new Feature({
        type: "route",
        geometry: new LineString(trackCar).transform("EPSG:4326", "EPSG:3857"),
      });
      console.log(trackCar);
      // 创建一个小车
      this.geoMarker = new Feature({
        type: "geoMarker",
        geometry: new Point(trackCar[0]).transform("EPSG:4326", "EPSG:3857"),
      });
      this.styles = {
        route: new Style({
          stroke: new Stroke({
            width: 2,
            color: "#ffc641",
          }),
        }),
        geoMarker: new Style({
          image: new Icon({
            scale: 0.1,
            src: require("../assets/logo.png"), //设置小车的图片，这里请使用require方式加载
            rotateWithView: true,
            rotation: -Math.atan2(
              trackCar[1][1] - trackCar[0][1],
              trackCar[1][0] - trackCar[1][0]
            ), //设置小车的位置偏移角度
          }),
        }),
      };
      // 把小车和线添加到图层
      this.vectorLayer = new VectorLayer({
        source: new VectorSource({
          features: [routeFeature, this.geoMarker],
        }),
        style: function (feature) {
          if (_that.animating && feature.get("type") === "geoMarker") {
            return null;
          }
          return _that.styles[feature.get("type")];
        },
      });
    },
    startAnimation() {
      if (this.animating) {
        this.stopAnimation(false);
      } else {
        this.animating = true;
        this.now = new Date().getTime();
        this.startbutton = "Cancel Animation";
        // hide geoMarker
        this.geoMarker.setStyle(null);
        // just in case you pan somewhere else
        // this.map.getView().setCenter(fromLonLat([120.9800615193, 29.1326618704]));
        console.log(this.vectorLayer);
        this.vectorLayer.on("postrender", (e) => {
          console.log(e);
          this.moveFeature(e);
        });
        this.map.render();
      }
    },
    startButton() {
      this.startAnimation();
    },
    moveFeature(e) {
      console.log(111);
      var vectorContext = getVectorContext(e);
      var frameState = e.frameState;
      if (this.animating) {
        var elapsedTime = frameState.time - this.now;
        // here the trick to increase speed is to jump some indexes
        // on lineString coordinates
        var index = Math.round((this.speed * elapsedTime) / 1000);
        if (index >= this.routeLength) {
          this.stopAnimation(true);
          return;
        }
        var currentPoint = new Point(this.trackCar[index]);
        var feature = new Feature(currentPoint);
        vectorContext.drawFeature(feature, this.styles.geoMarker);
      }
      // tell OpenLayers to continue the postrender animation
      this.map.render();
    },
  },
  mounted() {
    this.addTrack();
    this.initMap();
  },
};
</script>
<style lang="scss" scoped>
// 此处非核心，已删除
</style>
